package org.fatmansoft.teach.service;

import org.fatmansoft.teach.models.*;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import org.fatmansoft.teach.repository.*;
import org.fatmansoft.teach.util.CommonMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

@Service
@Transactional
public class HomeWorkService {

    @Autowired
    HomeWorkRepository homeWorkRepository;
    @Autowired
    CourseRepository courseRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    StudentRepository studentRepository;

    @Autowired
    StudentCourseRepository studentCourseRepository;

    @Autowired
    StudentHomeWorkRepository studentHomeWorkRepository;

    /**************************************辅助方法*********************************************/

    //用于主键自增
    public synchronized Integer getNewHomeWorkId() {
        Integer id = homeWorkRepository.getMaxId();
        if (id == null)
            id = 1;
        else
            id = id + 1;
        return id;
    }

    public synchronized Integer getNewStudentHomeWorkId() {
        Integer id = studentHomeWorkRepository.getMaxId();
        if (id == null)
            id = 1;
        else
            id = id + 1;
        return id;
    }


    //获取homeWork实体
    public HomeWork getHomeWork(Integer homeWorkId) {

        HomeWork homeWork = null;
        if (homeWorkId != null) {
            Optional<HomeWork> x1 = homeWorkRepository.findByHomeWorkId(homeWorkId);
            if (x1.isPresent()) {
                homeWork = x1.get();
            }
        }

        return homeWork;
    }

    public HomeWork getHomeWorkByHomeWorkName(String name) {
        HomeWork homeWork = null;
        if (name != null) {
            Optional<HomeWork> x = homeWorkRepository.findByHomeWorkName(name);
            if (x.isPresent()) {
                homeWork = x.get();
            }
        }
        return homeWork;
    }

    public HomeWork getHomeWorkByHomeWorkNameTime(String name, String time) {
        HomeWork homeWork = null;
        if (name != null && time != null) {
            Optional<HomeWork> x = homeWorkRepository.findHomeWorkByHomeWorkNameAndHomeWorkTime(name, time);
            if (x.isPresent()) {
                homeWork = x.get();
            }
        }
        return homeWork;
    }

    //获取作业对应课程
    public Course getCourseByName(String name) {
        Course course = null;
        if (name != null) {
            Optional<Course> x = courseRepository.findCourseByName(name);
            if (x.isPresent()) {
                course = x.get();
            }
        }
        return course;
    }


    //获取学生实体
    public Student getStudentByNum(String num) {
        Student student = null;
        if (num != null) {
            Optional<Student> x = studentRepository.findByPersonNum(num);
            if (x.isPresent()) {
                student = x.get();
            }
        }
        return student;
    }

    public Student getStudentByPersonId(Integer id) {
        Student student = null;
        if (id != null) {
            Optional<Student> x = studentRepository.findByPersonPersonId(id);
            if (x.isPresent()) {
                student = x.get();
            }
        }
        return student;
    }

    //获取用户
    public User getUser(Integer id) {
        User user = null;
        if (id != null) {
            Optional<User> x = userRepository.findById(id);
            if (x.isPresent()) {
                user = x.get();
            }
        }
        return user;
    }


    //获取学生端登录信息
    public Student getLoginStudent() {
        Integer userId = CommonMethod.getUserId();
        Student student = null;

        User user = getUser(userId);
        if (user != null) {
            Integer personId = user.getPerson().getPersonId();
            student = getStudentByPersonId(personId);
        }

        return student;
    }


    //获取单个homework的map用于返回
    public Map getMapFromHomeWork(HomeWork homeWork) {
        Map m = new HashMap();
        if (homeWork == null) {
            return m;
        }

        m.put("homeWorkId", homeWork.getHomeWorkId());
        m.put("homeWorkName", homeWork.getHomeWorkName());
        m.put("homeWorkTime", homeWork.getHomeWorkTime());
        m.put("courseName", homeWork.getCourse().getName());

        return m;
    }
    //将学生作业关联对象转换为Map
    public Map getMapFromStudentHomeWork(StudentHomeWork studentHomeWork) {
        Student student = studentHomeWork.getStudent();
        HomeWork homeWork = studentHomeWork.getHomeWork();
        Map m = new HashMap<>();
        System.out.println(student.getPerson().getPersonId());
        System.out.println(homeWork.getHomeWorkName());
        m.put("studentId", student.getPerson().getNum());
        m.put("studentName", student.getPerson().getName());
        m.put("homeWorkName", homeWork.getHomeWorkName());
        m.put("courseName", homeWork.getCourse().getName());
        m.put("homeWorkTime", homeWork.getHomeWorkTime());
        m.put("state", studentHomeWork.getState());
        m.put("score", studentHomeWork.getScore());
        m.put("homeWorkDetails",studentHomeWork.getHomeWorkDetails());
        return m;
    }

    //获取一系列homework用于返回
    public List getHomeWorkMapList(String nameTime) {
        List dataList = new ArrayList();
        List<HomeWork> homeWorkList = homeWorkRepository.findHomeWorkByNameTime(nameTime);
        if (homeWorkList == null || homeWorkList.size() == 0) {
            return dataList;

        }
        for (int i = 0; i < homeWorkList.size(); i++) {
            dataList.add(getMapFromHomeWork(homeWorkList.get(i)));
        }
        return dataList;
    }
    //获取学生作业关联用于返回
    public List getStudentHomeWorkByNameTime(String name, String time) {
        List datalist=new ArrayList<>();
        if (name != null && time != null) {
            List<StudentHomeWork> x=studentHomeWorkRepository.getStudentList(name,time);
            if (x != null && x.size() > 0) {
                System.out.println("查询成功");
                for (int i = 0; i < x.size(); i++) {
                    datalist.add(getMapFromStudentHomeWork(x.get(i)));
                }
            }
        }
        return datalist;
    }
    //获取单个学生作业关联用于返回
    public List getUniqueStudentHomeWorkByNameTime(String studentId,String name, String time) {
        List datalist=new ArrayList<>();
       if (name != null && time != null&& studentId != null) {
           List<StudentHomeWork> x=studentHomeWorkRepository.getStudentHomeWorkListUnique(studentId,name,time);
           if (x != null && x.size() > 0) {
               System.out.println("查询单个作业成功");
               System.out.println("查到的作业数量为"+x.size());
               for (int i = 0; i < x.size(); i++) {
                   datalist.add(getMapFromStudentHomeWork(x.get(i)));
               }
           }
       }
       return datalist;
    }


    /********************************************接口业务逻辑部分****************************************/
    //添加一个作业
    public DataResponse insertHomeWork(DataRequest dataRequest) {
        String homeWorkName = dataRequest.getString("homeWorkName");
        String homeWorkTime = dataRequest.getString("homeWorkTime");
        String courseName = dataRequest.getString("courseName");
        HomeWork homeWork = getHomeWorkByHomeWorkNameTime(homeWorkName, homeWorkTime);
        Course course = getCourseByName(courseName);
        if (homeWork == null) {
            homeWork = new HomeWork();
            homeWork.setHomeWorkId(getNewHomeWorkId());
            homeWork.setHomeWorkName(homeWorkName);
            homeWork.setHomeWorkTime(homeWorkTime);
            homeWork.setCourse(course);
        }
        homeWorkRepository.save(homeWork);
        return CommonMethod.getReturnMessageOK();
    }

    //删除一个作业
    public DataResponse deleteHomeWork(DataRequest dataRequest) {
        String homeWorkName = dataRequest.getString("homeWorkName");
        String homeWorkTime = dataRequest.getString("homeWorkTime");

        System.out.println("删除homeWorkName:"+homeWorkName);
        System.out.println("删除homeWorkTime:"+homeWorkTime);
        HomeWork homeWork = getHomeWorkByHomeWorkNameTime(homeWorkName, homeWorkTime);
        if (homeWork == null) {
            return CommonMethod.getReturnMessageError("没有这个作业");
        }
        studentHomeWorkRepository.deleteByHomeWork("",homeWork);
        homeWorkRepository.delete(homeWork);
        return CommonMethod.getReturnMessageOK();
    }

    //修改作业
    public DataResponse updateHomeWork(DataRequest dataRequest) {
        String homeWorkName = dataRequest.getString("homeWorkName");
        String homeWorkTime = dataRequest.getString("homeWorkTime");
        String courseName = dataRequest.getString("courseName");

        HomeWork homeWork = getHomeWorkByHomeWorkNameTime(homeWorkName, homeWorkTime);
        Course course = getCourseByName(courseName);
        if (homeWork == null) {
            return CommonMethod.getReturnMessageError("没有该作业");
        }
        Integer homeWorkId = homeWork.getHomeWorkId();
        homeWork = new HomeWork();
        homeWork.setHomeWorkId(homeWorkId);
        homeWork.setHomeWorkName(homeWorkName);
        homeWork.setHomeWorkTime(homeWorkTime);
        homeWork.setCourse(course);
        homeWorkRepository.save(homeWork);
        return CommonMethod.getReturnMessageOK();
    }

    //查询作业
    public DataResponse findByNameTime(DataRequest dataRequest) {
        String nameTime = dataRequest.getString("nameTime");
        List datalist = getHomeWorkMapList(nameTime);
        return CommonMethod.getReturnData(datalist);
    }

    /**************************************中间表部分*********************************************/
    //为所有学生布置作业
    public DataResponse assignHomeWork(DataRequest dataRequest) {
        String homeWorkName = dataRequest.getString("homeWorkName");
        String homeWorkTime = dataRequest.getString("homeWorkTime");
        String courseName = dataRequest.getString("courseName");
        HomeWork homeWork = getHomeWorkByHomeWorkNameTime(homeWorkName, homeWorkTime);
        if (homeWork == null) {
            insertHomeWork(dataRequest);
        }
        homeWork = getHomeWorkByHomeWorkNameTime(homeWorkName, homeWorkTime);

        List<StudentCourse> studentCourses = studentCourseRepository.findByCourseName(courseName);
        List<Student> students = new ArrayList<>();
        if(studentCourses.size()==0){
           return CommonMethod.getReturnMessageError("该课程无学生选课");
        }
        for (int i = 0; i < studentCourses.size(); i++) {
            students.add(studentCourses.get(i).getStudent());
            System.out.println(studentCourses.get(i).getStudent().getPerson().getName());
        }
        for (int i = 0; i < students.size(); i++) {
            StudentHomeWork studentHomeWork = new StudentHomeWork();
            studentHomeWork.setStudentHomeWorkId(getNewStudentHomeWorkId());
            studentHomeWork.setStudent(students.get(i));
            studentHomeWork.setHomeWork(homeWork);
            studentHomeWork.setState("未完成");
            studentHomeWork.setScore("0");
            studentHomeWorkRepository.save(studentHomeWork);
        }
        return CommonMethod.getReturnMessageOK("布置作业成功");
    }
    //教师为作业打分
    public DataResponse setHomeWorkScore(DataRequest dataRequest) {
        String homeWorkName = dataRequest.getString("homeWorkName");
        String homeWorkTime = dataRequest.getString("homeWorkTime");
        String studentId = dataRequest.getString("studentId");
        String score = dataRequest.getString("score");
        System.out.println("score="+score);
        StudentHomeWork studentHomeWork = studentHomeWorkRepository.getStudentHomeWork(studentId, homeWorkName, homeWorkTime).get();
        studentHomeWork.setScore(score);
        studentHomeWorkRepository.save(studentHomeWork);
        return CommonMethod.getReturnMessageOK();
    }
    //教师查找布置的所有作业
    public DataResponse findHomeWork(DataRequest dataRequest) {
        String homeWorkNameTime = dataRequest.getString("homeWorkNameTime");
        List datalist = getHomeWorkMapList(homeWorkNameTime);
        if(datalist.size() == 0) {
            return CommonMethod.getReturnMessageError("未查询到作业");
        }
        return CommonMethod.getReturnData(datalist);
    }
    //教师查找作业对应学生
    public  DataResponse findStudentHomeWork(DataRequest dataRequest) {
        String homeWorkName = dataRequest.getString("homeWorkName");
        String homeWorkTime = dataRequest.getString("homeWorkTime");
        System.out.println("homeWorkName="+homeWorkName+"正在查询中返回学生");
        List datalist = getStudentHomeWorkByNameTime(homeWorkName, homeWorkTime);
        if (datalist == null) {
            return CommonMethod.getReturnMessageError("查找不到学生");
        }
        else return CommonMethod.getReturnData(datalist);
    }
    //教师下载作业
    public DataResponse downloadHomeWork(DataRequest dataRequest) {
        String StudentId=dataRequest.getString("studentId");
        String homeWorkName = dataRequest.getString("homeWorkName");
        String homeWorkTime = dataRequest.getString("homeWorkTime");
        System.out.println(StudentId);
        System.out.println(homeWorkName);
        System.out.println(homeWorkTime);
        List datalist = getUniqueStudentHomeWorkByNameTime(StudentId,homeWorkName, homeWorkTime);
        System.out.println("返回作业下载"+datalist.size());
            return CommonMethod.getReturnData(datalist);

    }

    //学生提交作业
    public DataResponse setHomeWorkState(DataRequest dataRequest) throws IOException {
        Student student = getLoginStudent();
        String studentId = student.getPerson().getNum();
        String homeWorkName = dataRequest.getString("homeWorkName");
        String homeWorkTime = dataRequest.getString("homeWorkTime");
        String homeWorkDetails = dataRequest.getString("homeWorkDetails");
        StudentHomeWork studentHomeWork = studentHomeWorkRepository.getStudentHomeWork(studentId, homeWorkName, homeWorkTime).get();
        studentHomeWork.setState("已完成");
        studentHomeWork.setHomeWorkDetails(homeWorkDetails);
        studentHomeWorkRepository.save(studentHomeWork);
        return CommonMethod.getReturnMessageOK();

    }

    //学生查询作业
    public DataResponse getHomeWorkList(DataRequest dataRequest) {
        Student student = getLoginStudent();
        String studentId = student.getPerson().getNum();
        String homeWorkName = dataRequest.getString("homeWorkNameTime");
        List<StudentHomeWork> studentHomeWorkList = studentHomeWorkRepository.getHomeWorkList(studentId,homeWorkName);
        List datalist = new ArrayList();
        if (studentHomeWorkList.size() > 0) {
            for (int i = 0; i < studentHomeWorkList.size(); i++) {
                datalist.add(getMapFromStudentHomeWork(studentHomeWorkList.get(i)));
            }
            return CommonMethod.getReturnData(datalist);
        } else {
            return CommonMethod.getReturnMessageError("未查找到作业");
        }

    }
}